package com.gillion.grape.fros.ui.commands;

import java.util.ArrayList;
import java.util.List;

import net.java.amateras.uml.classdiagram.ClassDiagramEditor;
import net.java.amateras.uml.classdiagram.model.ClassModel;
import net.java.amateras.uml.model.AbstractUMLEntityModel;
import net.java.amateras.uml.model.RootModel;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.gef.EditPart;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IEditorActionDelegate;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.EditorPluginAction;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.progress.UIJob;

import com.gillion.grape.core.Logger;
import com.gillion.grape.fros.ui.Entity2ERUtils;


/**
 * 模型转换按钮
 * 
 * @author meichenhui
 * @since 2011-8-22
 *
 */
public class ModelTransform extends AbstractHandler implements IHandler,IEditorActionDelegate {
	public List<AbstractUMLEntityModel> list = new ArrayList<AbstractUMLEntityModel>();
	public void setActiveEditor(IAction action, IEditorPart targetEditor){
      this.run();
	}
	public void run(IAction action){
		IEditorPart page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
		final IFileEditorInput modelInput = (IFileEditorInput)page.getEditorInput(); // pim模型文件
		final String label = action.getText();
		StructuredSelection selected = (StructuredSelection)((EditorPluginAction)action).getSelection();
		List<EditPart> editPartList=selected.toList();//取到选定的类
		list.clear();
		for (EditPart anEditPart : editPartList) {
			if("AttributeEditPart".equals(anEditPart.getClass().getSimpleName())){//如果是属性生成实体或service，则返回
				return;
			};
			list.add((AbstractUMLEntityModel)anEditPart.getModel());
		}
		if (list.size() == 0 || (((EditPart)selected.getFirstElement()).getModel() instanceof RootModel)){
			boolean isGenerateAllEntities = MessageDialog.openConfirm(page.getSite().getShell(), "生成实体确认", "生成模块下的全部业务实体?");
			if (!isGenerateAllEntities){
				return;
			}
			list = Entity2ERUtils.deserializUMLDiagram(modelInput).getChildren();
		}
		
		UIJob job = new UIJob("模型转换") {
			@Override
			public IStatus runInUIThread(IProgressMonitor monitor) {
				Long start = System.currentTimeMillis();
				try {
					if ("cld".equals((modelInput.getFile().getFileExtension()))){ 
						Logger.logInfo("JAVA模型转换开始...");
						entityPIM2PSM(modelInput,label); // 实体模型转gfa模型
						Logger.logInfo("...JAVA模型转换结束");
						IFile gfaFile = modelInput.getFile().getProject().getFile(modelInput.getFile().getProjectRelativePath().toString().replaceAll("\\.cld", ".gfa"));
						Logger.logInfo("JAVA代码生成开始...");
						gfaModel2WefCode(new FileEditorInput(gfaFile),list,label); // gfa模型转换为代码
						Logger.logInfo("...JAVA代码生成结束");
					}
				} catch (Exception e) {
					Logger.logError(e);
				}
				Long end = System.currentTimeMillis();
			//	Logger.logInfo(Long.toString(end - start));
				return Status.OK_STATUS;
			}
		};
		job.schedule();
	}
	public void selectionChanged(IAction action, ISelection selection){
		
	}
	@Override
	public boolean isEnabled() {
		return true;
	}

	/**
	 * 
	 */
	@Override
	public Object execute(final ExecutionEvent event) throws ExecutionException {
		return null;
	}
	
	private void run(){
	}
	/**
	 * gfa模型转换为代码
	 * @param modelInput
	 *
	 * @author meichenhui
	 * @since 2011-8-30
	 *
	 */
	private void gfaModel2WefCode(IFileEditorInput modelInput,List<AbstractUMLEntityModel> list,String label) {
		// 模块名
		String moduleName = modelInput.getFile().getName().split("\\.")[0];
		GFAModel2FrosCode gfaModel2wefCode = new GFAModel2FrosCode(list);
		gfaModel2wefCode.setUnTransformModel(modelInput);
		gfaModel2wefCode.setModuleName(moduleName);
		gfaModel2wefCode.serializeTransformedModel(label);
	}

	/**
	 * 实体模型到PSM模型的转换
	 * @param umlModelInput
	 *
	 * @author meichenhui
	 * @since 2011-8-29
	 *
	 */
	private void entityPIM2PSM(IFileEditorInput umlModelInput,String label){
		// 模块名
		String moduleName = umlModelInput.getFile().getName().split("\\.")[0];
		// 实体模型转换为GFA模型
		EntityPIM2GFAModel entityModel2GFAModel = new EntityPIM2GFAModel();
		entityModel2GFAModel.setUnTransformModel(umlModelInput);
		entityModel2GFAModel.setModuleName(moduleName);
		entityModel2GFAModel.setTransformedArguments(umlModelInput.getFile().getProject().getLocationURI().getPath());
		entityModel2GFAModel.serializeTransformedModel(label);
	}
	
}
